const mongoose = require('mongoose')
const Movie = mongoose.model('Movie')



export const findAndRemove = async(id) => {
    const movie = await Movie.findOne({ _id: id })

    if (movie) {
        await movie.remove()
    }

}
export const findCount = async(type, year) => {
    let query = {}
    if (type) {
        query.movieTypes = {
            $in: [type]
        }
    }

    if (year) {
        query.year = year
    }
    const count = await Movie.find(query).count()

    return count
}

export const getAllMovies = async(params) => {
    // currentPage 当前页
    // pageSize 一页显示多少条
    // startIndex 从第几天开始
    // db.users.find().skip(pagesize*(n-1)).limit(pagesize)
    // type, year, currentPage, pageSize

    let movies = []

    let query = {}
    if (params.type) {
        query.movieTypes = {
            $in: [params[type]]
        }
    }

    if (params.year) {
        query.year = params.year
    }

    if (params.currentPage && params.pageSize) {
        params.currentPage = parseInt(params.currentPage)
        params.pageSize = parseInt(params.pageSize)
        movies = await Movie.find(query).sort({ "meta.createdAt": -1 }).skip(params.pageSize * (params.currentPage - 1)).limit(params.pageSize)
    } else {
        movies = await Movie.find(query)
    }

    return movies
}

export const getMovieDetail = async(id) => {
    const movie = await Movie.findOne({ _id: id })

    return movie
}

export const getRelativeMovies = async(movie) => {

    const movies = await Movie.find({
        movieType: {
            $in: movie.movieTypes
        }
    })

    return movies
}